// pages/chupan/chupan.js
Page({  
  data: {  
    questionDetail: {}, // 存储题目信息
    index: 0, // 当前题目下标
    userAnswers: {}, // 存储用户选择的答案
    correctAnswers: {}, // 存储正确答案
    answeredQuestions: [], // 存储已答题目的 ID
    showSelected: false,// 控制是否显示选中状态
    totalQuestions: 0,//总题目数 
    isAnswered:false,
  },

  onLoad(options) {  
    //console.log('接收到的参数:', options);  

    const { paperId, quId, index} = options;  
    this.setData({
      index: parseInt(index) // 设置当前题目下标
    }); 

    // 存储 paperId 和 quId 作为类的属性  
    this.paperId = paperId;   
    this.quId = quId;  

    // 获取题目列表并设置总题目数  
  const questions = wx.getStorageSync('papers');
  this.setData({  
    totalQuestions: questions.length // 更新总题目数  
  }); 
    // 获取题目详情  
    this.fetchQuestionDetail(this.paperId, this.quId);  
}  ,

  onShow() {
    this.fetchQuestionDetail(this.paperId,this.quId);
  },

  fetchQuestionDetail(paperId, quId) {  
    const that = this;
    const app = getApp();
      wx.request({  
          method: 'POST',  
          url: `${app.globalData.baseUrl}/paper/qu-detail`,  
          header: {  
            'authentication': 'eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MzI1NTg3MTcsInVzZXJJZCI6MTgyNzk5OTgyMTczMTA5ODYyNn0.SxS7ENOxgqgIh8AAn_Sw84R_zvFA99_khzsVNCDShLk'   
          },  
          data: {  
              paperId: paperId,  
              quId: quId  
          },  
          success(res) {  
            if (res.statusCode === 200 && res.data.code === 1) {
              const questionData = res.data.data;
              that.setData({
                questionDetail: questionData // 存储题目信息
              });
                
                const { answered,answerList } = questionData;
                // 处理用户答案  
          let selectedAnswerId = null;  
          if (answered) {  
            for (const answer of answerList) {  
              if (answer.checked) {  
                selectedAnswerId = answer.abc; // 获取用户选择的答案  
                break;  
              }  
            }  
          }  

          // 更新数据  
          that.setData({   
            userAnswers: {  
              ...that.data.userAnswers,  
              [quId]: selectedAnswerId // 更新用户答案  
            },  
            correctAnswers: {  
              ...that.data.correctAnswers,  
              [quId]: answerList.find(answer => answer.isRight) // 存储正确答案  
            },  
            showSelected: answered, // 标记是否显示选中状态  
            isAnswered:answered
          });
            } else {
              console.error('获取题目详情失败:', res.data);
            }
          },  
          fail(err) {  
              console.error('请求失败:', err);  
          }  
      });  
  }  ,

  // 处理上一题和下一题的点击事件
  onPrevQuestion() {
    const newIndex = this.data.index - 1;
    if (newIndex >= 0) {
      const questions = wx.getStorageSync(`papers`);
      const paperId = questions[newIndex].paperId; // 从题目列表中获取 paperId
      const quId = questions[newIndex].quId; // 从题目列表中获取 quId

      this.setData({ 
      index: newIndex,
      showSelected: true // 切换到新题目时重置显示状态
     });
      
      this.fetchQuestionDetail(paperId, quId); // 获取新的题目信息
    }
    else{
      wx.showToast({
        title:'已经是第一题了',
        icon:'error'
      });
    }
  },

  onNextQuestion() {
    const newIndex = this.data.index + 1;
    const questions = wx.getStorageSync(`papers`);
    
   // console.log('当前下标:', this.data.index);
   // console.log('新下标:', newIndex);
   // console.log('题目列表:', questions);
    
    if (newIndex < questions.length) {
      const paperId = questions[newIndex].paperId;
      const quId = questions[newIndex].quId;
      this.setData({ 
        index: newIndex,    
        showSelected: true // 切换到新题目时重置显示状态
       });
      this.fetchQuestionDetail(paperId, quId);

    } else {
      wx.showToast({
        title: '没有下一题了',
        icon: 'none'
      });
    }
  },

  onOptionSelect(event) {  
    const userAnswerValue = event.detail.value; // 获取用户选择的答案  
    const { quId, paperId, answerList } = this.data.questionDetail; // 获取当前题目的 quId 和 paperId  

    //检查是否选过了
    if(this.data.isAnswered) {
      wx.showToast({
        title:'此题以答',
        icon:'error'
      })
      return;//如果已经答过，终止函数
    }
    
    // 存储用户答案  
    this.setData({  
        userAnswers: {  
            ...this.data.userAnswers,  
            [quId]: userAnswerValue // 使用 quId 作为键  
        },  
        isAnswered:true, //固定已经答过的题目
        showSelected: true // 用户选择后不再显示选中状态  
    });  
    
    // 找到用户选择的答案  
    const selectedAnswer = answerList.find(item => item.abc === userAnswerValue);
      // 获取选中答案的 ID  
    const selectedAnswerId = selectedAnswer ? selectedAnswer.id : null; 

     // 找到正确答案  
     const correctAnswer = answerList.find(item => item.isRight === true); 
    // 更新状态  
    this.setData({  
        correctAnswers: {  
            ...this.data.correctAnswers,  
            [quId]: correctAnswer ? correctAnswer : null // 存储正确答案  
        },
       
    });  
    const app = getApp();
    // 发送请求判断答案  
    wx.request({  
        method: 'POST',  
        url: `${app.globalData.baseUrl}/paper/fill-answer`,  
        header: {  
            'authentication': 'eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MzI1NTg3MTcsInVzZXJJZCI6MTgyNzk5OTgyMTczMTA5ODYyNn0.SxS7ENOxgqgIh8AAn_Sw84R_zvFA99_khzsVNCDShLk'  
        },  
        data: {  
            answers: [selectedAnswerId], // 将选中答案的 ID 放入数组中  
            paperId: paperId,  
            quId: quId  
        },  
        success: (res) => {  
            if (res.statusCode === 200 && res.data.code === 1) {  
                console.log('答案判断成功');  
            } else {  
                console.error('获取答案判断失败:', res.data);  
            }  
        },  
        fail: (err) => {  
            console.error('请求失败:', err);  
        }  
    });  
},

renderAnswerrs() {
  const { answerList, quId, userAnswers } = this.data.questionDetail;
  return answeerList.map(item => {
    return {
      ...item,
      checked: userAnswers[quId] == item.abc
    }
  }) 
},

    // 返回到上一页  
    onGoBack() {  
      wx.navigateBack({
      }); 
    },  

    onGoackhome() { 
      wx.showModal({  
        title: '提示',  
        content: '是否要退出答题',  
        success: (res) => {   
            if (res.confirm) {  
        wx.switchTab({  
          url: `/pages/home/home`  
      });  
        console.log('用户点击确定');  
    } else if (res.cancel) {  
        console.log('用户点击取消');  
    } 
        },  
    });  
      
      
  },  
});